# 高并发，使用数据库连接池

from fastapi import FastAPI
import asyncpg.pool
 
app = FastAPI()
 
# 创建数据库连接池
async def create_db_connection():
    return await asyncpg.create_pool(user='root', password='123456', database='mes_node_data',port='3307',)
 
@app.on_event("startup")
async def startup():
    app.state.db = await create_db_connection()
 
@app.on_event("shutdown")
async def shutdown():
    # 关闭数据库连接池
    if hasattr(app.state, 'db'):
        await app.state.db.close()
 
@app.get("/users")
async def get_data():
    conn = app.state.db.acquire()
    
    try:
        # 在这里进行数据库查询等操作
        
        result = await conn.fetchrow('SELECT * FROM user')
        
        return {"result": result}
    finally:
        app.state.db.release(conn)

# 运行主函数
if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='127.0.0.1', port=8000)